import uvicorn
from fastapi import FastAPI  # 1. 导入 FastAPI
from fastapi.staticfiles import StaticFiles

from memoryscope import MemoryScope
from memoryscope.web.chat_item import ChatItem
from memoryscope.web.memory_item import MemoryItem

app = FastAPI()  # 2. 创建一个 FastAPI 实例

app.mount("/web/", StaticFiles(directory="web", html=True), name="web")

config_path = "/apps/aigc/memoryscope/demo_config_zh.yaml"
ms = MemoryScope(config_path=config_path)  # MemoryScope 只初始化一次
memory_chat = ms.default_memory_chat


@app.post('/chat')  # 3. 创建一个路径操作
async def chat(item: ChatItem):
    response = memory_chat.chat_with_memory(query=item.message, role_name=item.user)
    memory_chat.run_service_operation_backend("consolidate_memory", context=ms.context, role_name=item.user)
    return {'message': response.message.content}  # 5. 返回内容


@app.post('/memory')  # 3. 创建一个路径操作
async def memory(item: MemoryItem):
    response = memory_chat.list_memory(role_name=item.user)
    return {'message': response}  # 5. 返回内容


@app.post('/consolidateAndGet')  # 3. 创建一个路径操作
async def consolidateAndGet(item: ChatItem):
    memory_chat.addQueryMessageToMemory(query=item.message, role_name=item.user)
    memory_chat.run_service_operation_backend("consolidate_memory", context=ms.context, role_name=item.user)
    response = memory_chat.list_memory(role_name=item.user)
    return {'message': response}  # 5. 返回内容


if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=12000)
